package love.yuanmeng.guetcoalsystem.cotroller;

/*
 *   @Studio:CHJY · 源梦科技
 *   @Author:lzl
 *   @Ide:IntelliJ IDEA
 *   @Creation time:2021/10/10 15:41
 */

import love.yuanmeng.guetcoalsystem.service.RegisterService;
import love.yuanmeng.guetcoalsystem.vo.RegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;


@CrossOrigin
@RestController
public class RegisterController {

    @Autowired
    private RegisterService registerService;

    @RequestMapping("/register")
    public String register(@RequestBody RegisterVo registerVo){
        int result = registerService.doService(registerVo);
        if (result==0){
            return "register failed";
        }
        return "successfully";
    }

    @RequestMapping("/register/uploadImage")
    public String uploadImage(MultipartFile imageFile) throws FileNotFoundException {

        if (imageFile == null) {
            return "failed";
        }
        if (imageFile.getSize() > 1024 * 1024 * 10) {
            return "failed";
        }
        //获取文件后缀
        String suffix = imageFile.getOriginalFilename().substring(imageFile.getOriginalFilename().lastIndexOf(".") + 1, imageFile.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return "failed";
        }
        String savePath = ResourceUtils.getURL("classpath:static/img/").getPath();
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        String filename=imageFile.getOriginalFilename();
        try {
            //将文件保存指定目录
            imageFile.transferTo(new File(savePath + filename));
        } catch (Exception e) {
            e.printStackTrace();
            return "failed";
        }
        return "successfully";
    }

}
